package com.techpleiad.ieducation.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;

import com.techpleiad.ieducation.entity.UserAccount;
import com.techpleiad.ieducation.exception.ServiceException;
import com.techpleiad.ieducation.service.ILoginService;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	
	@Autowired
	private ILoginService loginService;

    /**
     * Default constructor. 
     */
    public LoginServlet() {
        // TODO Auto-generated constructor stub
    }

	@Override
	protected void process(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		try {
			UserAccount userAccount = this.loginService.login(username, password);
			if (null != userAccount) {
				response.sendRedirect("home.jsp");
			} else {
				request.setAttribute("errorMessage", "Invalid username or password");   
				RequestDispatcher dispatcher = getServletConfig().getServletContext().getRequestDispatcher("/pages/login.jsp");  
				dispatcher.forward( request, response);  
			}
		} catch (ServiceException e) {
			throw new ServletException(e);
		}
	}
	
	/**
	 * Sets the login service.
	 *
	 * @param loginService the new login service
	 */
	public void setLoginService(ILoginService loginService) {
		this.loginService = loginService;
	}

}
